<template>
  <el-dialog
    v-model="dialogVisible"
    title="体检详情"
    width="80%"
    :before-close="handleClose"
    class="checkup-detail-dialog"
  >
    <div v-if="record" class="checkup-detail">
      <!-- 基本信息 -->
      <el-card class="info-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>基本信息</span>
          </div>
        </template>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="info-item">
              <label>体检ID：</label>
              <span>{{ record.id }}</span>
            </div>
            <div class="info-item">
              <label>患者姓名：</label>
              <span>{{ record.patientName }}</span>
            </div>
            <div class="info-item">
              <label>联系电话：</label>
              <span>{{ record.patientPhone }}</span>
            </div>
            <div class="info-item">
              <label>体检套餐：</label>
              <span>{{ record.packageName }}</span>
            </div>
          </el-col>
          
          <el-col :span="12">
            <div class="info-item">
              <label>体检日期：</label>
              <span>{{ formatDate(record.checkupDate) }}</span>
            </div>
            <div class="info-item">
              <label>负责医生：</label>
              <span>{{ record.doctor }}</span>
            </div>
            <div class="info-item">
              <label>体检状态：</label>
              <el-tag :type="getStatusType(record.status)" size="small">
                {{ getStatusText(record.status) }}
              </el-tag>
            </div>
            <div class="info-item">
              <label>完成进度：</label>
              <el-progress
                :percentage="record.progress"
                :stroke-width="8"
                :show-text="true"
                style="width: 200px"
              />
            </div>
          </el-col>
        </el-row>
      </el-card>
      
      <!-- 时间信息 -->
      <el-card class="info-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>时间信息</span>
          </div>
        </template>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="info-item">
              <label>创建时间：</label>
              <span>{{ formatDateTime(record.createdAt) }}</span>
            </div>
          </el-col>
          
          <el-col :span="8">
            <div class="info-item">
              <label>开始时间：</label>
              <span>{{ record.startTime ? formatDateTime(record.startTime) : '未开始' }}</span>
            </div>
          </el-col>
          
          <el-col :span="8">
            <div class="info-item">
              <label>完成时间：</label>
              <span>{{ record.endTime ? formatDateTime(record.endTime) : '未完成' }}</span>
            </div>
          </el-col>
        </el-row>
      </el-card>
      
      <!-- 体检项目 -->
      <el-card class="info-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>体检项目</span>
            <el-button type="primary" size="small" @click="handleRefreshItems">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </template>
        
        <el-table :data="checkupItems" stripe style="width: 100%">
          <el-table-column prop="name" label="项目名称" width="200" />
          <el-table-column prop="category" label="项目分类" width="120" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getItemStatusType(row.status)" size="small">
                {{ getItemStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="result" label="检查结果" show-overflow-tooltip />
          <el-table-column prop="normalRange" label="正常范围" width="150" show-overflow-tooltip />
          <el-table-column prop="unit" label="单位" width="80" />
          <el-table-column prop="doctor" label="检查医生" width="100" />
          <el-table-column prop="completedAt" label="完成时间" width="150">
            <template #default="{ row }">
              {{ row.completedAt ? formatDateTime(row.completedAt) : '-' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="{ row }">
              <el-button
                v-if="row.status === 'pending'"
                type="success"
                size="small"
                text
                @click="handleStartItem(row)"
              >
                开始
              </el-button>
              <el-button
                v-if="row.status === 'in_progress'"
                type="primary"
                size="small"
                text
                @click="handleCompleteItem(row)"
              >
                完成
              </el-button>
              <el-button
                type="info"
                size="small"
                text
                @click="handleViewItem(row)"
              >
                详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        
        <el-button
          v-if="record && record.status === 'pending'"
          type="success"
          @click="handleStart"
        >
          <el-icon><VideoPlay /></el-icon>
          开始体检
        </el-button>
        
        <el-button
          v-if="record && record.status === 'in_progress'"
          type="warning"
          @click="handleRecord"
        >
          <el-icon><Edit /></el-icon>
          录入结果
        </el-button>
        
        <el-button
          v-if="record && record.status === 'in_progress' && record.progress === 100"
          type="primary"
          @click="handleComplete"
        >
          <el-icon><Check /></el-icon>
          完成体检
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'

// Props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  record: {
    type: Object,
    default: null
  }
})

// Emits
const emit = defineEmits(['update:visible', 'start', 'complete', 'record'])

// 响应式数据
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 模拟体检项目数据
const checkupItems = ref([
  {
    id: 1,
    name: '血常规',
    category: '血液检查',
    status: 'completed',
    result: '正常',
    normalRange: '4.0-10.0',
    unit: '×10^9/L',
    doctor: '张医生',
    completedAt: '2024-01-21 09:30:00'
  },
  {
    id: 2,
    name: '尿常规',
    category: '尿液检查',
    status: 'completed',
    result: '正常',
    normalRange: '阴性',
    unit: '',
    doctor: '李医生',
    completedAt: '2024-01-21 10:15:00'
  },
  {
    id: 3,
    name: '心电图',
    category: '心脏检查',
    status: 'in_progress',
    result: '',
    normalRange: '正常心律',
    unit: '',
    doctor: '王医生',
    completedAt: ''
  },
  {
    id: 4,
    name: 'B超检查',
    category: '影像检查',
    status: 'pending',
    result: '',
    normalRange: '无异常',
    unit: '',
    doctor: '',
    completedAt: ''
  },
  {
    id: 5,
    name: '胸部X光',
    category: '影像检查',
    status: 'pending',
    result: '',
    normalRange: '无异常',
    unit: '',
    doctor: '',
    completedAt: ''
  }
])

// 监听记录变化，更新体检项目
watch(() => props.record, (newRecord) => {
  if (newRecord) {
    // 根据体检进度更新项目状态
    updateItemsStatus(newRecord.progress)
  }
}, { immediate: true })

// 方法
const handleClose = () => {
  dialogVisible.value = false
}

const handleStart = () => {
  emit('start', props.record)
}

const handleComplete = () => {
  emit('complete', props.record)
}

const handleRecord = () => {
  emit('record', props.record)
}

const handleRefreshItems = () => {
  ElMessage.success('体检项目已刷新')
}

const handleStartItem = (item) => {
  item.status = 'in_progress'
  item.doctor = '当前医生'
  ElMessage.success(`已开始 ${item.name} 检查`)
}

const handleCompleteItem = (item) => {
  item.status = 'completed'
  item.completedAt = new Date().toLocaleString('zh-CN')
  item.result = '正常' // 模拟结果
  ElMessage.success(`${item.name} 检查已完成`)
  
  // 更新整体进度
  updateOverallProgress()
}

const handleViewItem = (item) => {
  ElMessage.info(`查看 ${item.name} 详情功能待实现`)
}

const updateItemsStatus = (progress) => {
  // 根据进度更新项目状态
  const completedCount = Math.floor((progress / 100) * checkupItems.value.length)
  
  checkupItems.value.forEach((item, index) => {
    if (index < completedCount) {
      item.status = 'completed'
      if (!item.completedAt) {
        item.completedAt = new Date().toLocaleString('zh-CN')
      }
      if (!item.result) {
        item.result = '正常'
      }
      if (!item.doctor) {
        item.doctor = '系统医生'
      }
    } else if (index === completedCount && progress < 100) {
      item.status = 'in_progress'
    } else {
      item.status = 'pending'
    }
  })
}

const updateOverallProgress = () => {
  const completedItems = checkupItems.value.filter(item => item.status === 'completed')
  const newProgress = Math.round((completedItems.length / checkupItems.value.length) * 100)
  
  if (props.record) {
    props.record.progress = newProgress
  }
}

const getStatusType = (status) => {
  const statusMap = {
    pending: 'warning',
    in_progress: 'primary',
    completed: 'success',
    cancelled: 'danger'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    pending: '待体检',
    in_progress: '体检中',
    completed: '已完成',
    cancelled: '已取消'
  }
  return statusMap[status] || '未知'
}

const getItemStatusType = (status) => {
  const statusMap = {
    pending: 'info',
    in_progress: 'warning',
    completed: 'success'
  }
  return statusMap[status] || 'info'
}

const getItemStatusText = (status) => {
  const statusMap = {
    pending: '待检查',
    in_progress: '检查中',
    completed: '已完成'
  }
  return statusMap[status] || '未知'
}

const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleDateString('zh-CN')
}

const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}
</script>

<style scoped>
.checkup-detail-dialog :deep(.el-dialog__body) {
  padding: 20px;
  max-height: 70vh;
  overflow-y: auto;
}

.checkup-detail {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.info-card {
  border: 1px solid #e4e7ed;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
  color: #2c3e50;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  font-size: 14px;
}

.info-item label {
  font-weight: 500;
  color: #606266;
  min-width: 80px;
  margin-right: 8px;
}

.info-item span {
  color: #2c3e50;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .checkup-detail-dialog {
    width: 95% !important;
  }
  
  .checkup-detail-dialog :deep(.el-dialog__body) {
    padding: 15px;
  }
  
  .info-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
  
  .info-item label {
    min-width: auto;
    margin-right: 0;
  }
  
  .dialog-footer {
    flex-direction: column;
  }
  
  .dialog-footer .el-button {
    width: 100%;
  }
  
  :deep(.el-table) {
    font-size: 12px;
  }
  
  :deep(.el-table .cell) {
    padding: 8px 4px;
  }
}

@media (max-width: 480px) {
  .card-header {
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
  }
  
  .card-header .el-button {
    width: 100%;
  }
}
</style>